package cn.sockstack.controller;

import cn.sockstack.entity.User;
import cn.sockstack.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @GetMapping(value = "login")
    public String login() {
        return "login";
    }
    @PostMapping(value = "login")
    public String doLogin(
            User user,
            HttpSession session,
            Model model
    )
    {
        User _user = userService.detail(user);
        if (_user == null) {
            model.addAttribute("error", "不存在该用户");
            return "login";
        }

        if (!user.getPassword().equals(_user.getPassword())) {
            model.addAttribute("error", "密码错误");
            return "login";
        }
        session.setAttribute("username", user.getUsername());
        return "redirect:/";
    }
}
